import { Injectable, HttpException } from '@nestjs/common'
import { Builder, Parser } from 'xml2js'

@Injectable()
export class XmlService {
  /*xml构建器，微信的xml请求体，根元素为xml */
  private readonly builder = new Builder({ rootName: 'xml' })
  /*xml解析器，默认忽略根元素，即xml元素，直接获取到包含请求参数的对象` */
  private readonly parser = new Parser({ trim: true, explicitArray: false, explicitRoot: false })

  constructor() {}

  /*构建xml为同步方法 */
  build(obj: any): string {
    return this.builder.buildObject(obj)
  }

  /*解析xml为异步方法 */
  async parse(xml: string): Promise<any> {
    let obj: any
    let ex: any = ''
    await new Promise((ok, no) => {
      this.parser.parseString(xml, (err, result) => {
        if (err) {
          ex = new HttpException('解析xml错误' + err.toString(), 404)
          ok()
          return
        } else {
          obj = result
          ok()
          return
        }
      })
    })
    if (ex) {
      throw ex
    } else {
      return obj
    }
  }
}
